package com.ruoyi.system.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.service.impl.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: cjie
 * @description:
 * @date: 2021/5/9
 */
@Api(tags = "文件上传下载")
@RestController
@RequestMapping("/file")
public class FileUploadController {
    @Resource
    private FileUploadService fileUploadService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value="文件上传", notes="文件上传")
    @PostMapping("/upload")
    public R<SysFile> upload(@RequestParam("file") MultipartFile file) throws Exception {
        return this.fileUploadService.upload(file);
    }

    /**
     * 文件删除
     *
     * @param key 指包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     * @return
     * @throws Exception
     */
    @ApiOperation(value="文件删除", notes="文件删除")
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("key") String key)
            throws Exception {
        return this.fileUploadService.delete(key);
    }

    /**
     * 查询oss上的所有文件
     * @param prefix 文件前缀
     * @return
     * @throws Exception
     */
    @ApiOperation(value="查询oss上的所有文件", notes="查询oss上的所有文件")
    @GetMapping("/list")
    public List<OSSObjectSummary> list(String prefix)
            throws Exception {
        return this.fileUploadService.list(prefix);
    }

    /**
     * 根据文件名下载oss上的文件
     *
     * @return
     * @Param objectName 指包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
     */
    @PreAuthorize(hasPermi = "system:file:download")
    @ApiOperation(value="下载oss上的文件", notes="下载oss上的文件")
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition" ,
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        this.fileUploadService.exportOssFile(response.getOutputStream(), objectName);
    }
}
